package com.tianruan.dc.modules.sys.user.security;

import com.alibaba.fastjson.JSONObject;
import com.tianruan.dc.common.constant.GlobalExceptionEnum;
import com.tianruan.dc.common.utils.response.VResponse;
import com.tianruan.dc.common.utils.JedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @PS 退出成功Handler
 */
@Configuration
public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {

    @Autowired(required = false)
    private TokenStore redisTokenStore;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {


        String access_token = request.getParameter("access_token");

        if (JedisUtils.exists("access:" + access_token)){
            JedisUtils.del("access:" + access_token);
            String refresh_token = JedisUtils.get("access_to_refresh:" + access_token);
            JedisUtils.del("access_to_refresh:" + access_token);
            JedisUtils.del("auth:" + access_token);
            JedisUtils.del("refresh:" + refresh_token);
            JedisUtils.del("refresh_auth:" + refresh_token);
            JedisUtils.del("refresh_to_access:" + refresh_token);
        }

        response.setStatus(HttpStatus.OK.value());
        try {
            response.setContentType("application/json;charset=utf-8");
            VResponse<Object> result = VResponse.result(GlobalExceptionEnum.LOGOUT_SUCCESS);
            response.getOutputStream().write(JSONObject.toJSONString(result).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println();
    }
}
